<template>
    <div id="app">
     <h2>SuShi会员管理系统</h2>
     <div class="login">
    <!-- 表单 -->
     <el-form
    ref="ruleForm"
    :model="ruleForm"
    :rules="rules"
    label-width="60px"
    class="demo-ruleForm"
  >
    <el-form-item label="账号:" prop="userName">
      <el-input v-model="ruleForm.userName"></el-input>
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input  show-password v-model="ruleForm.password"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')"
        >登录</el-button
      >
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
    </div>
    </div>
</template>

<script>
import {login} from "../api/index"
import router from "../router/index"
import { ElMessage } from 'element-plus'

export default {
  data() {
    return {
     ruleForm: {
        userName: '666666',
        password: '666666'
      },
      rules: {
        userName: [
          {
            required: true,
            message: '请输入账号',
            trigger: 'blur',
          },
          {
            min: 6,
            max: 12,
            message: '账号长度为6-12',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'change',
          },
          {
            min: 6,
            max: 12,
            message: '密码长度为6-12',
            trigger: 'blur',
          }
        ],
      },
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = JSON.stringify(this.ruleForm);
          console.log(this.ruleForm)
          login(this.ruleForm).then(res=>{
           if(res.data.code==200){
            //  将服务端返回的toke保存到本地的localstorage中
             localStorage.setItem("token",res.headers.authorization)
             //登录成功跳转到后台
             router.push("/home")
           }
           else{
           ElMessage.error("账号/密码错误 请重新登录")
           //登录失败 将账号密码信息清空
            this.$refs[formName].resetFields()
           }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
  },
}
</script>

<style scoped>
#app{
    width: 550px;
    height: 300px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    margin: 100px auto 0;
    border-radius: 10px;
}
#app h2{
    text-align: center;
    padding-top: 20px;
}
.login{
    margin: 40px auto 0px;
    width: 300px;
}
</style>